package com.st.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.jwt.util.JwtUtils;
import com.jwt.util.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>title: com.wfx.filters</p>
 * author zhuximing
 * description:网关的全局认证的过滤器
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //如果是登录请求，必须放行
        URI uri = request.getURI();
        if (uri.getPath().indexOf("login")>0||uri.getPath().indexOf("search")>0||uri.getPath().indexOf("check")>0||uri.getPath().indexOf("notify")>0
                ||uri.getPath().indexOf("codeLogin")>0||uri.getPath().indexOf("sendCode")>0||uri.getPath().indexOf("sendPigCode")>0||uri.getPath().indexOf("verifyCode")>0
                ||uri.getPath().indexOf("pigCode")>0||uri.getPath().indexOf("sendMsgCode")>0||uri.getPath().indexOf("register")>0||uri.getPath().indexOf("content")>0
                ||uri.getPath().indexOf("saveContent")>0||uri.getPath().indexOf("saveHot")>0
        ) {
           return chain.filter(exchange);//放行
        }


        //获取jwt令牌
        String jwtToken = exchange.getRequest().getHeaders().getFirst("token");
        if (jwtToken == null) {

            Map res = new HashMap(){{
                put("success",false);
                put("msg","必须登录");
            }};


           return response(response, res );


        }else{

            PublicKey publicKey = null;
            //加载公钥
            try {
                publicKey = RsaUtils.getPublicKey(  ResourceUtils.getFile("classpath:ras_public").getPath());

            } catch (Exception e) {
                e.printStackTrace();

            }

            try {
                //校验令牌
                Map infoFromToken = (Map) JwtUtils.getInfoFromToken(jwtToken, publicKey, Map.class);
//
//                //将用户信息向下传递
                ServerHttpRequest mutableReq = request.mutate().header("userId",  infoFromToken.get("userId")+"").build();
                ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

                return chain.filter(mutableExchange);//放行

//               return  chain.filter(exchange);

            }catch (MalformedJwtException ex){//jwt解析异常
                Map res = new HashMap(){{
                    put("success",false);
                    put("msg","jwt令牌不合法");
                }};
                return response(response, res );

            }catch (ExpiredJwtException exception){
                Map res = new HashMap(){{
                    put("success",false);
                    put("msg","jwt令牌过期");
                }};
                return response(response, res );
            }






        }


    }


    //指定过滤器的执行顺序，值越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }




    private Mono<Void> response(ServerHttpResponse response,Map res){
        //不能放行，直接返回，返回json信息
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");



        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());

        return response.writeWith(Flux.just(dataBuffer));//响应json数据
    }
}
